<?php

namespace App\Jobs\Finance\Traits;

trait CommonBillTrait
{
    //计算更新客户总账单数据
    public function calcUpdateCustomerBillTotal($customerBill){
        $customerBill->refresh();
        $accountBills=$customerBill->accountBills;
        $totalData=$this->getCustomerBillTotalData($accountBills);
        return $customerBill->update($totalData);
    }
    //
    public function getCustomerBillTotalData($accountBills){
        $data=[
            //本期费用合计
            'this_period_total'=>$this->calcCustomerThisPeriodTotal($accountBills),
            //上期应收金额
            'previous_period_receivable'=>$accountBills->sum('previous_receivable'),
            //汇款金额
            'received_total'=>$this->sumCustomerReceivedTotal($accountBills),
        ];
        $data['total_customer_pay']=$data['this_period_total']+$data['previous_period_receivable']-$data['received_total'];
        return $data;
    }
    public function calcCustomerThisPeriodTotal($accountBills){
        $groupTotal=$this->calcCustomerGroupTotal($accountBills);
        //本期服务报价核算
        $serviceQuoteFinal=$groupTotal['quote'];
        //店铺管理费/其他
        $shopOtherFee=$groupTotal['shop_fee'];
        //加班费
        $overTimeFee=$accountBills->sum('overtime_fee');
        //提成
        $commissionFee=$accountBills->sum('commission_fee');

        return $serviceQuoteFinal+$shopOtherFee+$overTimeFee+$commissionFee;
    }
    //期服务报价核算,店铺管理费/其他
    public function calcCustomerGroupTotal($accountBills){
        $quote=[];
        $shopFee=[];
        foreach ($accountBills as $a){
            $quote[$a->quotation_group_id]=$a->service_quote_final;
            $shopFee[$a->shop_id]=$a->shop_other_fee;
        }
        return [
            'quote'=>array_sum($quote),
            'shop_fee'=>array_sum($shopFee),
        ];
    }
    //计算所有回款项
    public function sumCustomerReceivedTotal($accountBills){
        return $accountBills->sum('pdd_received')+$accountBills->sum('previous_reserved')+$accountBills->sum('deposit_cost')+$accountBills->sum('penalty_amount');
    }

}
